package com.zw.hrm.service.impl;

import com.alibaba.fastjson.JSON;
import com.zw.hrm.domain.Sso;
import com.zw.hrm.domain.VipBase;
import com.zw.hrm.dto.RegisterDTO;
import com.zw.hrm.dto.SMSSendDTO;
import com.zw.hrm.feignclients.RedisFeignClient;
import com.zw.hrm.mapper.SsoMapper;
import com.zw.hrm.mapper.VipBaseMapper;
import com.zw.hrm.service.ISsoService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.zw.hrm.util.AjaxResult;
import com.zw.hrm.util.encrypt.MD5;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.UUID;

/**
 * <p>
 * 会员登录账号 服务实现类
 * </p>
 *
 * @author zw
 * @since 2020-03-02
 */
@Service
public class SsoServiceImpl extends ServiceImpl<SsoMapper, Sso> implements ISsoService {
    @Autowired
    private RedisFeignClient redisFeignClient;
    @Autowired
    private VipBaseMapper vipBaseMapper;

    @Override
    public void register(RegisterDTO registerDTO) {
        //参数判断
        String phone = registerDTO.getMobile();
        String password = registerDTO.getPassword();
        String smsCode = registerDTO.getSmsCode();
        if( !StringUtils.hasLength(phone) ||
                !StringUtils.hasLength(password) ||
                !StringUtils.hasLength(smsCode)){
            throw new RuntimeException("无效的参数");
        }

        //判断手机验证码是否正确 -> 获取Redis发送记录 ， 和参数中的验证码比较
        String smsCodeRedisKey = "sms:"+phone;
        AjaxResult smsAjaxResult = redisFeignClient.get(smsCodeRedisKey);
        if(!smsAjaxResult.isSuccess() || smsAjaxResult.getResultObj() == null){
            throw new RuntimeException("无效的手机验证码");
        }

        String redisSmsCode = JSON.parseObject(smsAjaxResult.getResultObj().toString(), SMSSendDTO.class).getCode();
        if(!redisSmsCode.equals(smsCode)){
            throw new RuntimeException("手机验证码错误");
        }

        //判断手机是否已经被注册
        Sso sso = baseMapper.selectByPhone(phone);
        if(sso != null){throw new RuntimeException("手机号已经被注册");}

        //保存sso到数据库

        long time = new Date().getTime();
        Sso registerSso = new Sso();
        registerSso.setCreateTime(time);
        registerSso.setPhone(registerDTO.getMobile());

        //密码：加密，加盐
        String salt = MD5.getRandomCode(16);

        String enPass = MD5.getMD5(registerDTO.getPassword() + salt);
        registerSso.setPassword(enPass);
        registerSso.setSalt(salt);


        baseMapper.insert(registerSso);

        //5.保存base表
        VipBase vipBase = new VipBase();
        vipBase.setSsoId(registerSso.getId());

        vipBase.setCreateTime(time);
        vipBase.setRegTime(time);
        vipBase.setRegChannel(1); // 1.PC端注册

        vipBaseMapper.insert(vipBase);
    }

    @Override
    public String login(Sso sso) {
        //参数验证
        if (!StringUtils.hasLength(sso.getPassword()) || !StringUtils.hasLength(sso.getPhone())){
            throw new RuntimeException("参数异常，登录失败");
        }

        //从数据库中拿用户对象,并比对用户手机号，密码是否匹配
        Sso user = baseMapper.selectByPhone(sso.getPhone());
        if (user == null){
            throw new RuntimeException("无此用户");
        }
        if (!user.getPhone().equals(sso.getPhone())){
            throw  new RuntimeException("用户名错误");
        }
        String password = MD5.getMD5(sso.getPassword() + user.getSalt());
        if (!password.equals(user.getPassword())){
            throw new RuntimeException("密码错误");
        }

        //账号密码通过验证，生成token，存入redis，并将token返回前端
        String token = UUID.randomUUID().toString();
        AjaxResult ajaxResult = redisFeignClient.setex(token, 30 * 60, JSON.toJSONString(user));
        if (!ajaxResult.isSuccess()){
            throw new RuntimeException("登录失败，令牌操作异常");
        }
        return token;
    }
}
